﻿#include "widget.h"
#include "ui_widget.h"

/*****************************************************************
    initServerSignals()
    初始化信号槽
    将服务器端的函数与获取的信号相关联
********************************************************************/
void Widget::initServerSignals()
{
    connect(&m_server, SIGNAL(newConnection()), this, SLOT(onServerNewConnection()));
}

/*****************************************************************
    startServer()
    启动服务器
    在localPort显示本地端口号
********************************************************************/
bool Widget::startServer()
{
    if(m_server.listen(QHostAddress::AnyIPv4,ui->ipPort->text().toInt()))       //只监听IPV4的所有客户端
    {
        ui->targetLabel->show();
        ui->targetObject->show();
        ui->localPort->setText(QString("%1").arg(m_server.serverPort()));
        return true;
    }
    else
       return false;
}

/******************************************************************
    onServerNewConnection()
    获取客户端连接进入的信息，
    在targetObject（对象下拉框）添加信息，同时提醒新客户端的连入
    并且初始化关联相关信号和槽
*******************************************************************/
void Widget::onServerNewConnection()
{
    qDebug() << "onNewConnection";
    QTcpSocket* tcp = m_server.nextPendingConnection();     //获取新的客户端信息
    QString info=tcp->peerAddress().toString()+":"+QString("%1").arg(tcp->peerPort());
    ui->targetObject->addItem(info);
    QMessageBox::information(this,"提示",QString("新的客户端连入:%1").arg(info),QMessageBox::Ok);
    tcp->setObjectName(info);       //设置名称,方便查找
    connect(tcp, SIGNAL(disconnected()), this, SLOT(onServerDisconnected()));
    connect(tcp, SIGNAL(readyRead()), this, SLOT(onServerDataReady()));
    connect(tcp, SIGNAL(bytesWritten(qint64)), this, SLOT(onServerBytesWritten(qint64)));
}

/*****************************************************************
    onServerDisconnected()
    客户连接断开函数
    检测客户端连接信息，当有客户退出时，将连接对象相关信息删除，并发出提醒
********************************************************************/
void Widget::onServerDisconnected()
{
    QTcpSocket* tcp = dynamic_cast<QTcpSocket*>(sender());
    if( tcp != NULL )       //从连接对象中移除掉
    {
        qDebug() << "onServerDisconnected";
        qDebug() << "Local Address:" << tcp->peerAddress();
        qDebug() << "Local Port:" << tcp->peerPort();
        QString info=tcp->peerAddress().toString()+":"+QString("%1").arg(tcp->peerPort());
        QMessageBox::information(this,"提示",QString("客户端断开连接:%1").arg(info),QMessageBox::Ok);

        int index = ui-> targetObject ->findText(info);
        if(index>=0)
        ui->targetObject->removeItem(index);
    }
}

/*****************************************************************
    onServerDataReady()
    信息接受函数
    获取客户端发来的信息，并在recvEdit上显示
********************************************************************/
void Widget::onServerDataReady()
{
    QTcpSocket* tcp = dynamic_cast<QTcpSocket*>(sender());
    if(tcp->peerAddress().toString()!=targetAddr || tcp->peerPort()!=targetPort  )
    {
        targetAddr = tcp->peerAddress().toString();
        targetPort = tcp->peerPort();
        ui->recvEdit->insertPlainText("[接受来自"+ targetAddr+":"+QString("%1").arg(targetPort)+"]:\r\n");
    }
    ui->recvEdit->moveCursor(QTextCursor::End);
    ui->recvEdit->insertPlainText(QString::fromLocal8Bit(tcp->readAll())+"\r\n");
}

/*****************************************************************
    onServerBytesWritten(qint64 bytes)
    更新下方sendLenLabel（发送条数）信息
********************************************************************/
void Widget::onServerBytesWritten(qint64 bytes)
{
    qDebug() << "onBytesWritten:" << bytes;
    ui->sendLenLabel->setText(QString("%1").arg(ui->sendLenLabel->text().toInt()+bytes));
}
